package cn.lichenes.controller;

import cn.lichenes.entity.Record;
import cn.lichenes.service.RecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Controller
public class RecordController {

    @Autowired
    private RecordService recordService;

    @GetMapping("/management-record")
    public String managementRecord(
            @RequestParam(value = "page",defaultValue = "1") Integer page,
            @RequestParam(value = "beginTime",defaultValue = "2020-01-11") Date beginTime,
            @RequestParam(required = false) Date endTime, Model model){
        String str = null;
        SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss" );
        Calendar calendar = Calendar.getInstance();
        if (endTime == null){
            Date date = new Date();
            endTime = date;
            calendar.setTime(date);
        }else {
            calendar.setTime(endTime);
        }
        str = sdf.format(endTime);
        calendar.add(Calendar.DATE, +1);
        endTime = calendar.getTime();
        Map<String,Object> map = new HashMap<>();
        map.put("endTime",str.split(" ")[0]);
        System.out.println(beginTime+","+endTime);
        Page<Record> recordPage = recordService.findAll(page,beginTime,endTime);
        map.put("records",recordPage.getContent());
        map.put("currentPage",page);
        map.put("totalPages",recordPage.getTotalPages());
        str = sdf.format(beginTime);
        map.put("beginTime",str.split(" ")[0]);
        model.addAllAttributes(map);
        return "management-record";
    }
}
